﻿/*
 * Copyright (C) 2012, Jesus Requejo <jesus.requejo@gmail.com> 
 * Licensed under Microsoft Public License (Ms-PL)
 * http://www.microsoft.com/en-us/openness/licenses.aspx#MPL
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace LoaderServiceManager {
   public partial class UsersCheckList : Form {

      private IList<string> decoratedAvailableUsers;
      private bool someoneIsAdmin;
      public IList<string> SelectedUsers { get; set; }

      protected UsersCheckList() {
         InitializeComponent();
      }

      public UsersCheckList(IList<string> decoratedAvailableUsers, bool someoneIsAdmin, string title, string label)
         : this() {
         userIsAdminLabel.Visible = false;
         if (someoneIsAdmin) {
            userIsAdminLabel.Text = "* user is an administrator";
            userIsAdminLabel.Visible = true;
         }
         this.decoratedAvailableUsers = decoratedAvailableUsers;
         this.someoneIsAdmin = someoneIsAdmin;
         this.Text = title;
         this.label1.Text = label;
         SelectedUsers = new List<string>();
         InitializeListView();
         FillListView();
      }

      private void InitializeListView() {
         usersList.CheckBoxes = true;
         usersList.View = View.Details;
         usersList.GridLines = true;
         // I have to do this ugly workaround with a listView because CheckboxList sucks so terribly
         this.usersList.Columns.Add("HiddenColumSoDetailsViewWorks");
         this.usersList.Columns[0].Width = this.usersList.Width - SystemInformation.VerticalScrollBarWidth - 2 * usersList.Margin.Left;
         this.usersList.HeaderStyle = ColumnHeaderStyle.None;
      }

      private void FillListView() {
         var listViewCollection = decoratedAvailableUsers.Select(s => new ListViewItem(s)).ToArray();
         usersList.Items.AddRange(listViewCollection);
      }

      private void okButton_Click(object sender, EventArgs e) {
         var items = usersList.CheckedItems;
         var userNames = items.Cast<ListViewItem>().Select(item => item.Text).OrderBy(s => s);
         SelectedUsers = userNames.ToList();
         Close();
      }

      private void cancelButton_Click(object sender, EventArgs e) {
         Close();
      }
   }
}
